using Microsoft.Extensions.Logging;
using ModelContextProtocol.AspNetCore;
using ModelContextProtocol.Server;
using System.ComponentModel;
using ConsoleApi.Models;
using ConsoleApi.Services.Interfaces;

namespace ConsoleApi.Services;

/// <summary>
/// 增强的MCP工具服务 - 提供生产分析和预警功能
/// </summary>
[McpServerToolType]
public class EnhancedMcpToolService
{
    private readonly ILogger<EnhancedMcpToolService> _logger;
    private readonly IRealWeatherService _weatherService;
    private readonly IWeatherAlertRuleEngine _ruleEngine;
    private readonly IProductionDataService _productionService;

    public EnhancedMcpToolService(
        ILogger<EnhancedMcpToolService> logger, 
        IRealWeatherService weatherService,
        IWeatherAlertRuleEngine ruleEngine,
        IProductionDataService productionService)
    {
        _logger = logger;
        _weatherService = weatherService;
        _ruleEngine = ruleEngine;
        _productionService = productionService;
    }

    /// <summary>
    /// 获取城市天气信息
    /// </summary>
    [McpServerTool(Name = "get-weather")]
    [Description("获取指定城市的天气信息，包括当前天气和7天预报")]
    public async Task<string> GetWeatherAsync(
        [Description("城市名称，如：北京、上海、广州")] string city)
    {
        try
        {
            _logger.LogInformation("MCP工具被调用: get-weather, 城市: {City}", city);
            
            var weatherData = await _weatherService.GetWeatherByCityAsync(city);
            
            var result = $"📍 {weatherData.City}天气信息\n";
            result += $"🕐 更新时间: {weatherData.LastUpdated:yyyy-MM-dd HH:mm:ss}\n\n";
            
            if (weatherData.Current != null)
            {
                result += $"🌡️ 当前天气: {weatherData.Current.Temp}°C\n";
                result += $"☁️ 天气状况: {weatherData.Current.Text}\n";
                result += $"💨 风速: {weatherData.Current.WindSpeed}km/h\n";
                result += $"🧭 风向: {weatherData.Current.WindDir}\n";
                result += $"💧 湿度: {weatherData.Current.Humidity}%\n";
                result += $"🌡️ 气压: {weatherData.Current.Pressure}hPa\n";
                result += $"👁️ 能见度: {weatherData.Current.Vis}km\n\n";
            }
            
            if (weatherData.Forecast != null)
            {
                result += "📅 7天预报:\n";
                foreach (var day in weatherData.Forecast.Take(7))
                {
                    result += $"• {day.Date:MM/dd}: {day.Text} {day.MinTemp}°C~{day.MaxTemp}°C\n";
                }
            }
            
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取天气信息失败: {City}", city);
            return $"获取{city}天气信息失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 生产影响分析
    /// </summary>
    [McpServerTool(Name = "analyze-production-impact")]
    [Description("分析天气对生产活动的影响")]
    public async Task<string> AnalyzeProductionImpactAsync(
        [Description("城市名称")] string city,
        [Description("生产活动类型：户外作业/物流运输/设备维护")] string activityType = "户外作业")
    {
        try
        {
            _logger.LogInformation("MCP工具被调用: analyze-production-impact, 城市: {City}, 活动: {Activity}", city, activityType);
            
            var analysis = await _ruleEngine.AnalyzeProductionImpactAsync(city, activityType);
            
            var result = $"🏭 {city}生产影响分析\n";
            result += $"📊 活动类型: {activityType}\n";
            result += $"🕐 分析时间: {analysis.AnalysisTime:yyyy-MM-dd HH:mm:ss}\n";
            result += $"⚠️ 风险等级: {GetRiskLevelText(analysis.RiskLevel)}\n\n";
            
            // 当前天气影响
            if (analysis.CurrentWeather != null)
            {
                result += "🌡️ 当前天气影响:\n";
                result += $"• 温度: {analysis.CurrentWeather.Temp}°C\n";
                result += $"• 天气: {analysis.CurrentWeather.Text}\n";
            }
            
            // 预警信息
            if (analysis.Alerts.Any())
            {
                result += "\n🚨 预警信息:\n";
                foreach (var alert in analysis.Alerts.Take(5))
                {
                    result += $"• {alert.ActivityName}: {alert.Impact}\n";
                }
            }
            
            // 建议措施
            if (analysis.Recommendations.Any())
            {
                result += "\n💡 建议措施:\n";
                foreach (var rec in analysis.Recommendations.Take(5))
                {
                    result += $"• {rec}\n";
                }
            }
            
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "生产影响分析失败: {City}, {Activity}", city, activityType);
            return $"生产影响分析失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 获取生产建议
    /// </summary>
    [McpServerTool(Name = "get-production-recommendations")]
    [Description("获取基于天气的生产建议")]
    public async Task<string> GetProductionRecommendationsAsync(
        [Description("城市名称")] string city,
        [Description("生产活动类型")] string activityType = "户外作业")
    {
        try
        {
            _logger.LogInformation("MCP工具被调用: get-production-recommendations, 城市: {City}, 活动: {Activity}", city, activityType);
            
            var recommendations = await _ruleEngine.GetProductionRecommendationsAsync(city, activityType);
            
            var result = $"💡 {city}生产建议 - {activityType}\n";
            result += $"🕐 生成时间: {recommendations.GeneratedAt:yyyy-MM-dd HH:mm:ss}\n";
            result += $"⚠️ 风险等级: {GetRiskLevelText(recommendations.RiskLevel)}\n\n";
            
            if (recommendations.Recommendations.Any())
            {
                result += "📋 建议措施:\n";
                foreach (var rec in recommendations.Recommendations)
                {
                    result += $"• {rec}\n";
                }
            }
            
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取生产建议失败: {City}, {Activity}", city, activityType);
            return $"获取生产建议失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 获取天气趋势
    /// </summary>
    [McpServerTool(Name = "get-weather-trends")]
    [Description("获取城市天气趋势分析")]
    public async Task<string> GetWeatherTrendsAsync(
        [Description("城市名称")] string city)
    {
        try
        {
            _logger.LogInformation("MCP工具被调用: get-weather-trends, 城市: {City}", city);
            
            var trends = await _ruleEngine.GetWeatherTrendsAsync(city);
            
            var result = $"📈 {city}天气趋势分析\n";
            result += $"🕐 分析时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\n\n";
            
            if (trends.Any())
            {
                result += "📊 趋势变化:\n";
                foreach (var trend in trends.Take(7))
                {
                    result += $"• {trend.Date:MM/dd}: ";
                    
                    if (trend.TemperatureChange > 0)
                        result += $"温度上升{trend.TemperatureChange}°C ";
                    else if (trend.TemperatureChange < 0)
                        result += $"温度下降{Math.Abs(trend.TemperatureChange)}°C ";
                    else
                        result += "温度稳定 ";
                    
                    result += $"| {trend.Trend}\n";
                }
            }
            
            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取天气趋势失败: {City}", city);
            return $"获取天气趋势失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 获取系统状态信息
    /// </summary>
    [McpServerTool(Name = "get-system-status")]
    [Description("获取MCP系统状态信息")]
    public string GetSystemStatus()
    {
        _logger.LogInformation("MCP工具被调用: get-system-status");
        
        var result = "🔧 MCP系统状态信息\n";
        result += $"🕐 检查时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\n";
        result += $"✅ 系统状态: 正常运行\n";
        result += $"🌐 服务地址: http://localhost:5197\n";
        result += $"🔌 MCP端点: /mcp\n";
        result += $"📊 可用工具数量: 5个\n";
        result += $"💾 内存使用: 正常\n";
        result += $"🔄 最后更新: {DateTime.Now:yyyy-MM-dd HH:mm:ss}\n";
        
        return result;
    }

    // 辅助方法
    private string GetRiskLevelText(RiskLevel level) => level switch
    {
        RiskLevel.Low => "低风险",
        RiskLevel.Medium => "中风险",
        RiskLevel.High => "高风险",
        RiskLevel.Critical => "极高风险",
        _ => "未知"
    };

    private string GetSeverityText(AlertSeverity severity) => severity switch
    {
        AlertSeverity.Low => "低级",
        AlertSeverity.Medium => "中级",
        AlertSeverity.High => "高级",
        AlertSeverity.Critical => "极高级",
        _ => "未知"
    };

    private string GetPriorityText(Priority priority) => priority switch
    {
        Priority.Low => "低",
        Priority.Medium => "中",
        Priority.High => "高",
        Priority.Critical => "极高",
        _ => "未知"
    };
} 